<!DOCTYPE html>
<html>

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script src="https://cdn.staticfile.org/jquery/2.1.4/jquery.min.js" type="text/javascript"></script>
        <script>
			ws = new WebSocket("ws://192.168.0.166:2346");
			ws.onopen = function() {
				if(!name)
			    {
			        name = prompt('输入你的名字：', '');
				    if(!name || name=='null'){  
				        name = '游客';
				    }
			    }
			    login_data = '{"type":"login","username":"'+name.replace(/"/g, '\\"')+'","data":"login success"}';
			    ws.send(login_data);	
			};
			ws.onmessage = function(e) {
				var data = JSON.parse(e.data);
				switch(data.type)
				{
					case 'pong':
						pong_data = '{"type":"pong","username":"'+name.replace(/"/g, '\\"')+'","data":"pong"}';
						console.log('收到心跳')
						break;
					case 'say' :
						var data = eval("("+e.data+")");
						var item = "<p>"+data['username']+"：" + data['data'] +"</p>";
						$('#magList').prepend(item)
						break;
					default:
						break;	   
				}
			};
		 	
		    var sendMsg = function(){
		    	var msg = $("#msg").val();
		    	say_data = '{"type":"say","username":"'+name+'","data":"'+msg+'"}';
		     	ws.send(say_data);	
		     }
		</script>
</html>
    </head>
    <body>
		<input  id='msg' type='test' value=''/>
		<button onclick="sendMsg()">发送</button>
		<div id="magList"></div>		
    </body>
		